package com.yunmaozj.tools.lock.interceptor;

import com.yunmaozj.tools.lock.annotations.AnnotationDistributedLockAttributeSource;
import com.yunmaozj.tools.lock.annotations.DistributedLock;
import org.springframework.aop.ClassFilter;
import org.springframework.aop.support.StaticMethodMatcherPointcut;
import org.springframework.core.annotation.AnnotationUtils;

import java.io.Serializable;
import java.lang.reflect.Method;

/**
 * @author 钟明宏
 * @version V1.0
 * @date 2021-08-30 13:29
 **/
abstract class DistributedLockAttributePointcut extends StaticMethodMatcherPointcut implements Serializable {

    public DistributedLockAttributePointcut() {
        setClassFilter(new DistributedLockAttributeSourceClassFilter());
    }

    @Override
    public boolean matches(Method method, Class<?> targetClass) {
        AnnotationDistributedLockAttributeSource das = getTransactionAttributeSource();
        return (das == null || das.getTransactionAttribute(method, targetClass) != null);
    }

    protected abstract AnnotationDistributedLockAttributeSource getTransactionAttributeSource();

    private class DistributedLockAttributeSourceClassFilter implements ClassFilter {
        @Override
        public boolean matches(Class<?> targetClass) {
            return AnnotationUtils.isCandidateClass(targetClass, DistributedLock.class);
        }
    }
}
